package com.hpf.community.handler;

import cn.hutool.json.JSONUtil;
import com.hpf.community.utils.StandardResult;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

/**
 * @Description:
 * @Author: hpf
 * @Date: 2020/4/18 15:55
 */
@ControllerAdvice
public class DefaultExceptionHandler {

    /**
     * 没有权限异常
     * 后续根据不同的需求定制即可
     */
    @ExceptionHandler({UnauthorizedException.class})
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ModelAndView processUnauthenticatedException(NativeWebRequest request,
                                                        UnauthorizedException ex, HttpServletResponse response) {
        try{
            StandardResult result = new StandardResult();
            result.setCode(500);
            result.setMsg("You don't have this module's auth!");
            result.setState(false);
            PrintWriter out = response.getWriter();
            response.setContentType("text/html;charset=UTF-8");
            out.print(JSONUtil.parseObj(result));
            out.flush();
            out.close();
        }catch(Exception e){
            e.printStackTrace();
        }

        return null;
    }

}
